package leetcode.n2021;

import java.util.HashMap;
import java.util.Map;

/**
 * 有效的括号
 * https://leetcode-cn.com/problems/valid-parentheses/
 * @author Chaos
 * @date 2021/6/2
 */
public class IsValid {

    public static void main(String[] args) {
        IsValid test = new IsValid();
        System.out.println(test.test("()[]{}"));
        System.out.println(test.test("(){}}{"));
        System.out.println(test.test("([)]"));
        System.out.println(test.test("[[[]"));
    }


    public boolean test(String s) {

        boolean flag = false;

        HashMap map = new HashMap<String, String>();
        map.put("(",")");
        map.put("{","}");
        map.put("[","]");

        String[] ss = s.split("");
        String a = "";
        String b = "";

        for (int i = 0; i < ss.length; i++) {
            if (ss.length % 2 != 0) {
                return false;
            }
            if ("(".equals(ss[i]) || "{".equals(ss[i]) || "[".equals(ss[i])) {
                a += ss[i];
            } else {
                if (i == 0) {
                    return false;
                }
                if (a.length() == 0) {
                    return false;
                }
                if (map.get(a.split("")[a.length() - 1]).equals(ss[i])) {
                    flag = true;
                    a = a.substring(0,a.length() -1);
                } else {
                    flag = false;
                    break;
                }
            }
        }

        if (!a.equals("")) {
            return false;
        }

        return flag;
    }
}
